<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Canvas Animation</title>
    <style>
        body {
            height: 200vh;
        }
        .r {
            height: 500px;
            width: 500px;
            position: relative;
            margin: 20px; /* 添加一些间距，便于查看多个 .r */
        }
        img {
            width: 100%;
            height: 100%;
            position: absolute;
            top: 0;
            left: 0;
            opacity: 0;
        }
        img.on {
            opacity: 1;
        }
    </style>
</head>
<body>
<div class="r" data-total-images="39"></div>
<div class="r" data-total-images="20"></div>
<!-- 可以添加更多 .r -->

<script src="js/jquery-1.11.0.min.js"></script>
<script>
    function loadImages(container, totalImages) {
        var index_img = '';
        for (let i = 0; i < totalImages; i++) {
            index_img += '<img src="images/pro/' + container.data('index') + '/p_' + i + '.webp" alt="">';
        }
        container.append(index_img);
        container.find('img').first().addClass('on'); // 默认给第一个 img 添加类 on
    }

    function updateImages(container, scrollTop) {
        var start = container.position().top;
        var end = start + container.height();
        var imgElements = container.find('img');

        if (scrollTop >= start && scrollTop <= end) {
            var currentIndex = Math.floor((scrollTop - start) / (end - start) * imgElements.length);
            imgElements.removeClass('on');
            imgElements.eq(currentIndex).addClass('on');
        } else {
            imgElements.removeClass('on');
        }

        if (scrollTop >= end) {
            imgElements.last().addClass('on');
        } else if (scrollTop < start) {
            imgElements.first().addClass('on');
        }
    }

    window.addEventListener('scroll', function () {
        var scrollTop = window.pageYOffset || document.documentElement.scrollTop || document.body.scrollTop;
        $('.r').each(function () {
            var container = $(this);
            updateImages(container, scrollTop);
        });
    });

    // 初始化每个 r 的图片
    $(document).ready(function() {
        $('.r').each(function(index) {
            var container = $(this);
            container.data('index', index + 1); // 给每个 r 赋一个数据属性，以便加载对应的图片
            loadImages(container, parseInt(container.data('total-images'))); // 一次性加载所有图片
        });
    });
</script>
</body>
</html>
